package edu.chl.vrangogym.auth;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filter for redirecting a user to the logged in area if the session is 
 * still valid.
 * @author habbbe
 */
public class IndexRedirectFilter implements Filter {

    private FilterConfig config;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        String root = req.getServletContext().getContextPath();
        
        Object user = ((HttpServletRequest) req).getSession().getAttribute(
                "Auth.user");
        
        if (user != null) {
            ((HttpServletResponse) resp).sendRedirect(root + "/app/index.xhtml");
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void destroy() {
        config = null;
    }
}